<template>
  <div class="original-site-table">
    <div class="top-wrap">
      <div v-if="isWeight" class="label w-[240px]">权重</div>
      <div
        class="label min-w-[326px] flex-1"
        :class="{ '!w-446px': !isWeight }">
        域名/IP
      </div>
      <div
        class="label min-w-[326px] flex-1"
        :class="{ '!w-446px': !isWeight }">
        端口
      </div>
      <div class="label w-[64px]">操作</div>
    </div>
    <div class="container1">
      <source-site
        v-for="(item, index) in sourceList"
        :key="item.uuid"
        ref="refs"
        v-model:priority="item.priority"
        v-model:host="item.host"
        v-model:port="item.port"
        class="container-table"
        :disable-delete="sourceList.length === 1"
        :primary="isWeight && index === 0"
        @priority-change="validate(['priority'])"
        @host-change="validate(['host'])"
        @delete="sourceList.splice(index, 1)"></source-site>
    </div>
    <div
      class="h-12 flex-center text-sm/22px gap-x-6px text-primary cursor-pointer border border-t-solid border-color-#f1f2f3"
      @click="appendSource">
      <i-icons-table-add /> 添加一行
    </div>
  </div>
</template>

<script setup lang="ts">
import { v4 as uuidV4 } from 'uuid'

import { A_PRIORITY_TYPE } from '@/constants/site'
import SourceSite from './SourceSite.vue'
import type { ISourceSite } from './types'

interface IEmit {
  (event: 'update:list', value: ISourceSite[]): void
}

interface IProps {
  list: ISourceSite[]
  algorithm: string
}

const emit = defineEmits<IEmit>()
const props = defineProps<IProps>()

const refs = ref()
const sourceList = useVModel(props, 'list', emit)
const isWeight = computed(() => props.algorithm === A_PRIORITY_TYPE.WEIGHT)
// 添加一个新源站
function appendSource() {
  sourceList.value.push({
    uuid: uuidV4(),
    priority: +sourceList.value[sourceList.value.length - 1].priority + 1,
    host: '',
    port: null
  })
}

function validate(fields?: string[]) {
  return Promise.all(refs.value.map((item) => item.validate(fields)))
}

provide('sourceList', sourceList)
provide('priorityType', toRef(props, 'algorithm'))

defineExpose({ validate })
</script>

<style scoped lang="less">
.original-site-table {
  @apply rounded w-full min-w-952px;
  border: 1px solid #f1f2f3;
  .top-wrap {
    @apply h-12 py-1.5 flex items-center;
    .label {
      @apply text-4 text-sm/22px px-4 font-700;
      &:last-child {
        @apply mr-0;
      }
    }
  }
  .container {
    @apply max-h-250px overflow-auto;
  }
}
</style>
